package ro.fortech.workshop_demo.access.webservice;

import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * User: florinv
 * Date: 7/30/12
 * Time: 11:33 AM
 */
public abstract class JSONParser implements ResponseHandler<String> {
    protected int responseCode = -1;

    /**
     * Construct a string from an input stream
     *
     * @param in : input stream
     * @return the string read form the input stream
     * @throws java.io.IOException
     */
    protected String read(InputStream in) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line);
        }
        in.close();
        return sb.toString();
    }

    protected abstract void parse(HttpResponse httpResponse) throws JSONException, IOException;

    /**
     * Called when a connection exception occurs
     */
    protected abstract void connectionFailed();
}
